package com.yyfax.ph.personal.message;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import butterknife.BindView;
import butterknife.Unbinder;
import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.yyfax.common.CLog;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.Divider;
import com.yyfax.common.recyclerview.FooterLoadMoreView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.adapter.BaseRetryRecyclerAdapter;
import com.yyfax.ph.common.widgets.shortbadger.ShortcutBadger;
import com.yyfax.ph.personal.authority.jpush.PushInfoReceiver;
import com.yyfax.ph.personal.bindapply.BindApplyActivity;
import com.yyfax.ph.personal.mymoney.cash.CashActivity;
import com.yyfax.ph.progress.detail.ProgressDetailActivity;

import java.util.List;

/**
 * 消息页面
 * Created by ZhangXian on 2017/11/1.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class MessageActivity extends BaseYYFaxActivity implements MsgPresenter.View,
		BaseRetryRecyclerAdapter.RetryClickListener, OnRefreshListener, OnLoadMoreListener, MsgAdapter.OnClickListener {
	private static final String TAG = MessageActivity.class.getSimpleName();
	private static final int LOADER_ID = 1014;

	@BindView(R.id.info_list_view)
	IRecyclerView mListView;
	Unbinder unbinder;

	private FooterLoadMoreView mLoadMoreView;

	private MsgAdapter mAdapter;
	private BaseRetryRecyclerAdapter statesAdapter;

	private int mPageNum = 1;
	private int mPageSize = 20;
	private boolean mIsRefreshing = false;
	private boolean mNeedRefresh = false;

	private MsgPresenter mPresenter;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, MessageActivity.class);
		aty.startActivity(intent);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (null != intent && intent.hasExtra(PushInfoReceiver.FROM_PUSH_FLAG))
			mNeedRefresh = intent.getBooleanExtra(PushInfoReceiver.FROM_PUSH_FLAG, false);
		CLog.i(TAG, "onCreate mNeedRefresh = " + mNeedRefresh);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new MsgPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		CLog.i(TAG, "onLoadFinished");
		mPresenter = (MsgPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mNeedRefresh) {
			mNeedRefresh = false;
			mListView.post(new Runnable() {
				@Override
				public void run() {
					mListView.setRefreshing(true);
				}
			});
			ShortcutBadger.removeCount(this);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		onRefresh();
		ShortcutBadger.removeCount(this);
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		nm.cancelAll();
	}

	@Override
	public int getContentViewRes() {
		return R.layout.message_activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(R.string.message);
		mListView.setLayoutManager(new LinearLayoutManager(this));
		mListView.addItemDecoration(new Divider(DensityUtil.dip2px(this, 10), YJPH.getInstance().color(R.color.color_efefef), false, 0, 0, 0, 0, 0));
		mLoadMoreView = (FooterLoadMoreView) mListView.getLoadMoreFooterView();
		View noNetworkLayout = getLayoutInflater().inflate(R.layout.state_view_no_network, mListView, false);
		View emptyLayout = getLayoutInflater().inflate(R.layout.message_state_view_no_data, mListView, false);
		mAdapter = new MsgAdapter(this);
		mListView.setAdapter(mAdapter);
		statesAdapter = new BaseRetryRecyclerAdapter(mAdapter, null, emptyLayout, noNetworkLayout);
		statesAdapter.setRetryClickListener(this);
		mListView.setIAdapter(statesAdapter);
		mListView.setOnRefreshListener(this);
		mListView.setOnLoadMoreListener(this);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(LOADER_ID);
	}

	private void loadPage(boolean isRefresh) {
		mPageNum = isRefresh ? 1 : ++mPageNum;
		boolean loginSuccess = YJPH.getInstance().getPreferenceManager().isLoginSuccess();
		if (loginSuccess) {
			mPresenter.getMsgList(mPageNum, mPageSize);
		}
	}

	@Override
	public void onRetry() {
		onRefresh();
	}

	@Override
	public void onRefresh() {
		CLog.i(TAG, "onRefresh");
		loadPage(true);
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		mListView.setRefreshing(true);
		mIsRefreshing = true;
	}

	@Override
	public void onLoadMore() {
		if (FooterLoadMoreView.Status.THE_END != mLoadMoreView.getStatus()) {
			loadPage(false);
		} else {
			hadNoMore();
		}
		mIsRefreshing = false;
	}

	private void refreshFinish() {
		mIsRefreshing = false;
		mListView.setRefreshing(false);
	}

	@Override
	public void refreshMsgSuccess(List<MsgModel.MsgInfo> list) {
		if (mIsRefreshing) {
			refreshFinish();
			if (null != list && list.size() > 0) {
				statesAdapter.setState(StatesAdapter.STATE_NORMAL);
				mAdapter.removeAll();
				mAdapter.addData(list);
				mAdapter.notifyDataSetChanged();
				mListView.scrollToPosition(0);
			} else {
				checkEmpty(false);
			}
		}
	}

	@Override
	public void loadMoreMsgSuccess(List<MsgModel.MsgInfo> list) {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.LOADING);
		if (null == list || list.size() == 0) {
		} else {
			statesAdapter.setState(StatesAdapter.STATE_NORMAL);
			mAdapter.addData(list);
			mAdapter.notifyDataSetChanged();
		}

		if ((mAdapter.getCount() % mPageSize) > 0 && mPageNum != 1) {
			hadNoMore();
		}
	}

	@Override
	public void getMsgFailure() {
		mPageNum--;
		refreshFinish();
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (mPageNum == 1) {
			checkEmpty(true);
			showToast(R.string.load_failed);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				checkEmpty(true);
			}
		});
	}

	private void hadNoMore() {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		showToast(R.string.has_no_more);
	}

	private void checkEmpty(boolean isLoadDataError) {
		refreshFinish();
		if (mPageNum == 1) {
			if (isLoadDataError) {
				statesAdapter.setState(StatesAdapter.STATE_ERROR);
			} else {
				statesAdapter.setState(StatesAdapter.STATE_EMPTY);
			}
		}
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void setMsgRead(boolean readFlag) {
	}

	/**
	 * 点击跳转到消息详情页面
	 */
	@Override
	public void onClick(MsgModel.MsgInfo msg) {
		switch (msg.target) {
			//跳转到进度详情
			case MsgModel.TARGET_PROGRESS:
				ProgressDetailActivity.start(this, msg.refId);
				break;
			//跳转到子账号管理
			case MsgModel.TARGET_SUBACCOUNT:
				BindApplyActivity.start(this);
				break;
			//跳转到返现明细
			case MsgModel.TARGET_CASH_DETAIL:
				CashActivity.start(this);
				break;
			default:
				break;
		}
	}
}